import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainLayout from '../layouts/MainLayout.vue'

// 懒加载组件
const Dashboard = () => import('../views/Dashboard.vue')
const AnnualPlans = () => import('../components/AnnualPlans.vue')
const MonthlyPlans = () => import('../components/MonthlyPlans.vue')
const WeeklyPlans = () => import('../components/WeeklyPlans.vue')
const WeeklyReports = () => import('../components/WeeklyReports.vue')
const TeamOverview = () => import('../components/TeamOverview.vue')
const EmployeeManagement = () => import('../components/EmployeeManagement.vue')

const routes = [
  { path: '/login', name: 'Login', component: Login },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      { path: '', redirect: '/dashboard' },
      { path: 'dashboard', name: 'Dashboard', component: Dashboard },
      // 计划管理
      { path: 'plans/annual', name: 'AnnualPlans', component: AnnualPlans },
      { path: 'plans/monthly', name: 'MonthlyPlans', component: MonthlyPlans },
      { path: 'plans/weekly', name: 'WeeklyPlans', component: WeeklyPlans },
      // 报告管理
      { path: 'reports/weekly', name: 'WeeklyReports', component: WeeklyReports },
      // 经理专属
      { path: 'team/overview', name: 'TeamOverview', component: TeamOverview, meta: { role: 'manager' } },
      { path: 'team/employees', name: 'EmployeeManagement', component: EmployeeManagement, meta: { role: 'manager' } },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const user = JSON.parse(localStorage.getItem('user') || '{}')

  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.role && user.role !== to.meta.role) {
    next('/dashboard') // 权限不足跳回主页
  } else {
    next()
  }
})

export default router